package com.xmb.wcapi.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xmb.wcapi.constant.*;
import com.xmb.wcapi.dto.DutyAgoSaDTO;
import com.xmb.wcapi.entity.*;
import com.xmb.wcapi.mapper.*;
import com.xmb.wcapi.service.*;
import com.xmb.wcapi.util.*;
import com.xmb.wcapi.vo.BaseInventoryVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpStatus;
import org.apache.poi.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ForeignApiServiceImpl implements ForeignApiService {


    @Autowired
    private InventoryMapper inventoryMapper;

    @Autowired
    private DutyMapper dutyMapper;

    @Autowired
    private DutyAgoDataMapper dutyAgoDataMapper;

    @Autowired
    private DjBaseMaterialMapper djBaseMaterialMapper;

    @Autowired
    private BaseInventoryMapper baseInventoryMapper;

    @Value("${guard.baseUrl}")
    private String baseUrl;

    @Value("${guard.Id}")
    private String Id;

    @Value("${guard.Pwd}")
    private String Pwd;

    @Resource
    IStockNowService stockNowService;


    @Override
    public LayTableR getInventoryAgo(Integer page, Integer limit, String cusCode, String material, String invDef) {
        Page<BaseMaterial> baseMaterialPage = getBaseMaterialPage(page, limit, cusCode, material, invDef);
        return LayTableR.result(0,baseMaterialPage.getTotal(),baseMaterialPage.getRecords());
    }

    private Page<BaseMaterial> getBaseMaterialNew(String cusCode, String material, String invDef) {

        QueryWrapper<BaseMaterial> wrapper = new QueryWrapper<>();
        wrapper.like(StringUtils.isNotEmpty(cusCode),"cus_code",cusCode);
        wrapper.like(StringUtils.isNotEmpty(material),"dj_material",material);
        wrapper.eq("checked",true);
        wrapper.and(StringUtils.isNotEmpty(invDef),obj -> obj.like("type_of_machine",invDef) .or()
                .like("material_mrk",invDef)
        );
        //查询出来的数据是已经去过重的了
        Page<BaseMaterial> baseMaterialPage = new Page<>();
        List<BaseMaterial> baseMaterialListNew = djBaseMaterialMapper.getBaseMaterialListNew(wrapper);
        baseMaterialPage.setRecords(baseMaterialListNew);
        if (!baseMaterialPage.getRecords().isEmpty()){
            //查询统计
            List<BaseMaterial> baseMaterialSum = getBaseMaterialSum(cusCode, baseMaterialPage.getRecords());
            baseMaterialPage.getRecords().clear();
            baseMaterialPage.getRecords().addAll(baseMaterialSum);
        }
        return baseMaterialPage;
    }



    private Page<BaseMaterial> getBaseMaterialPage(Integer page, Integer limit, String cusCode, String material, String invDef) {

        QueryWrapper<BaseMaterial> wrapper = new QueryWrapper<>();
        wrapper.like(StringUtils.isNotEmpty(cusCode),"cus_code",cusCode);
        wrapper.like(StringUtils.isNotEmpty(material),"dj_material",material);
        wrapper.eq("checked",true);
        wrapper.and(StringUtils.isNotEmpty(invDef),obj -> obj.like("type_of_machine",invDef) .or()
                .like("material_mrk",invDef)
        );
        //查询出来的数据是已经去过重的了
        Page<BaseMaterial> baseMaterialPage = djBaseMaterialMapper.getBaseMaterialList(new Page<>(page,limit),wrapper);
        if (!baseMaterialPage.getRecords().isEmpty()){
            //查询统计
            List<BaseMaterial> baseMaterialSum = getBaseMaterialSum(cusCode, baseMaterialPage.getRecords());
            baseMaterialPage.getRecords().clear();
            baseMaterialPage.getRecords().addAll(baseMaterialSum);
        }

        return baseMaterialPage;
    }

    /**
     * 根据料号获取库存
     * @param cusCode 供应商编码
     * @param baseMaterialPage 本地料号数据 （已勾选数据）
     * @return
     */
    private List<BaseMaterial> getBaseMaterialSum(String cusCode, List<BaseMaterial> baseMaterialPage) {
        List<String> materials = baseMaterialPage.stream().filter(obj -> !obj.getClassType().equals("A"))
                .map(BaseMaterial::getDjMaterial).collect(Collectors.toList());
        List<BaseInventory> inventory = new ArrayList<>();
        if (!materials.isEmpty()){
            inventory = baseInventoryMapper.getMaterialInventory(cusCode, materials, null);
        }
        Map<String, List<BaseInventory>> detailsMap = inventory.stream().collect(Collectors.groupingBy(BaseInventory::getDjMaterial));

        List<String> mater = baseMaterialPage.stream().filter(obj -> obj.getClassType().equals("A"))
                .map(BaseMaterial::getDjMaterial).collect(Collectors.toList());
        List<BaseInventory> materialInventory = new ArrayList<>();
        if (!mater.isEmpty()){
            materialInventory = baseInventoryMapper.getMaterialInventory(cusCode, mater, "true");
        }
        Map<String, List<BaseInventory>> materialsMap = materialInventory.stream().collect(Collectors.groupingBy(BaseInventory::getDjMaterial));

        List<BaseMaterial> listNew = new ArrayList<>();
        for (BaseMaterial record : baseMaterialPage) {
            //只有在辅料的时候才会 客户料号和东矩料号取反
            if (record.getClassType().equals("C") || record.getClassType().equals("H")){
                String djMaterial = record.getDjMaterial();
                if (StringUtils.isNotEmpty(djMaterial)){
                    record.setCusMaterial(djMaterial);
                    record.setDjMaterial("");
                }
            }
            //是半成品的时候显示 制程
            if (record.getClassType().equals("B")){
                if (StringUtils.isNotEmpty(record.getMaterialMrk())){
                    for (DepConstant value : DepConstant.values()) {
                        if (record.getMaterialMrk().contains(value.getCode())){
                            record.setCusMaterial(value.getMessage());
                        }else if (record.getDjMaterial().contains(value.getCode())){
                            record.setCusMaterial(value.getMessage());
                        }
                    }
                }
            }
            if (record.getClassName().equals("塑件")){
                record.setClassName("辅材");
            }
            record.setClassName(record.getClassName()+"仓");
            record.setSum(0l);
            if (record.getClassType().equals("A")){
                List<BaseInventory> baseInventories = materialsMap.get(record.getDjMaterial());

                record.setClassName(MaterialTypeConstant.getMessage("10")+"仓");
                record.setSum(0l);

                BaseMaterial maTwo = new BaseMaterial();
                BeanUtil.copyProperties(record,maTwo);
                maTwo.setCusCode(record.getCusCode());
                maTwo.setCusName(record.getCusName());
                maTwo.setClassName(MaterialTypeConstant.getMessage("34")+"仓");
                maTwo.setSum(0l);

                BaseMaterial maTree = new BaseMaterial();
                BeanUtil.copyProperties(record,maTree);
                maTree.setCusCode(record.getCusCode());
                maTree.setCusName(record.getCusName());
                maTree.setClassName(MaterialTypeConstant.getMessage("18")+"仓");
                maTree.setSum(0l);

                if (null != baseInventories && !baseInventories.isEmpty()){

                    Map<String, List<BaseInventory>> collect = baseInventories.stream().collect(Collectors.groupingBy(BaseInventory::getPositionId));
                    if (!collect.isEmpty()){
                        for (String key : collect.keySet()) {
                            double in = collect.get(key).stream().mapToDouble(BaseInventory::getInSum).sum();
                            double out = collect.get(key).stream().mapToDouble(BaseInventory::getOutSum).sum();
                            BigDecimal sum = BigDecimal.valueOf(in).subtract(BigDecimal.valueOf(out));
                            if (key.equals("10")){
                                //外验ok
                                record.setSum(sum.longValue());
                            } else  if (key.equals("34")){
                                //待验
                                maTwo.setSum(sum.longValue());
                            }else if (key.equals("18") || key.equals("53")){
                                //不良重工
                                maTree.setSum(maTree.getSum() + sum.longValue());
                            }
                        }
                    }
                }
//                listNew.add(record);
                listNew.add(maTwo);
                listNew.add(maTree);
            } else {
                List<BaseInventory> baseInventories = detailsMap.get(record.getDjMaterial());
                if (null == baseInventories){
                    baseInventories = detailsMap.get(record.getCusMaterial());
                }
                if (null != baseInventories && !baseInventories.isEmpty()){
                    //统计库存数量
                    double inSum = baseInventories.stream().mapToDouble(BaseInventory::getInSum).sum();
                    double outSum = baseInventories.stream().mapToDouble(BaseInventory::getOutSum).sum();
                    long sum = BigDecimal.valueOf(inSum).subtract(BigDecimal.valueOf(outSum)).longValue();
                    record.setSum(sum);
                }
            }

        }
        listNew.addAll(baseMaterialPage);
        return listNew;
    }

    @Override
    public LayTableR getInventoryAgoNext(String cusCode, String material,String invDef) {
        Page<BaseMaterial> baseMaterialPage = getBaseMaterialNew(cusCode, material, invDef);
        //替换半成品 总数
        //获取现存量
        List<StockNow> list1 = stockNowService.list();
        Map<String, StockNow> collect1 = list1.stream().collect(Collectors.groupingBy(StockNow::getMaterial, Collectors.collectingAndThen(Collectors.toList(), val -> val.get(0))));
        for (BaseMaterial record : baseMaterialPage.getRecords()) {
            if (StringUtils.isNotEmpty(record.getDjMaterial())){
                StockNow stockNow = collect1.get(record.getDjMaterial());
                if (null != stockNow){
                    if (!record.getClassType().equals("A")){
//                        if (record.getClassName().equals("外验ok仓")){
//                            record.setSum(stockNow.getMaterialSum());
//                        }
                        record.setSum(stockNow.getMaterialSum());
                    }
                }
            }
        }
        List<String> strings = baseMaterialPage.getRecords().stream().map(BaseMaterial::getDjMaterial).collect(Collectors.toList());
        if (!strings.isEmpty()){
            //获取库存配置
            List<Inventory> list = inventoryMapper.selectList(Wrappers.lambdaQuery(Inventory.class)
                    .in(Inventory::getMaterial, strings)
            );
            if (!list.isEmpty()){
                Map<String, List<Inventory>> listMap = list.stream().collect(Collectors.groupingBy(Inventory::getMaterial));
                for (BaseMaterial record : baseMaterialPage.getRecords()) {
                    //配置
                    List<Inventory> inventories = listMap.get(record.getDjMaterial());
                    if (null != inventories){
                        Map<String, List<Inventory>> collect = inventories.stream().collect(Collectors.groupingBy(obj -> obj.getStoreName()+"仓"));
                        List<Inventory> inventoryList = collect.get(record.getClassName());
                        //数量小于标准值
                        if (null != inventoryList && !inventoryList.isEmpty()){
                            Inventory inventory = inventoryList.get(0);
                            Long sum = record.getSum();
                            Long sta = StringUtils.isEmpty(inventory.getStandard()) ? 0 : Long.parseLong(inventory.getStandard());
                            if (sum < sta){
                                record.setSum(sum + sta + Long.parseLong(inventory.getGrowUp()));
                            }
                        }
                    }
                }
            }
        }
        return LayTableR.result(0,baseMaterialPage.getTotal(),baseMaterialPage.getRecords());
    }

    public boolean loginDuty(){
        try {
            UniHttpUtil.getCookieStore(baseUrl+GuardConstant.LOGIN_URL,Id, DigestUtils.md5Hex(Pwd));
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    private JSONObject getUniResultData(String whereBuffer){
        //查询考勤机上的数据
        UniResult uniResult = null;
        // 根据personCode查询人员信息
        String queryPersonUrl = baseUrl + GuardConstant.URL_ATTENDANCEDEATIL + whereBuffer;
        try {
            uniResult = UniHttpUtil.sendHttpGetJson(queryPersonUrl, null);
            if (null == uniResult) {
                //当前数据库中没有对应人员信息, 直接新增
                return null;
            }
            if (HttpStatus.SC_OK != uniResult.getErrCode()) {
                return null;
            }
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        JSONObject jsonObject = JSONObject.parseObject(uniResult.getData().toString());
        return jsonObject;
    }

    @Override
    public LayTableR getDutyAgo(Integer page, Integer limit, String time, String endTime) {
        return getDutyList(page, limit, time,endTime);
    }

    private LayTableR getDutyList(Integer page, Integer limit, String startTime, String endTime){
        //判断是否登录
        if (!loginDuty()  || StringUtils.isEmpty(startTime) || StringUtils.isEmpty(endTime)){
            return null;
        }

        List<DutyAgo> list = getDutyAgos(startTime, endTime);
        return LayTableR.result(0, list.size(), list);
    }

    private List<DutyAgo> getDutyAgos(String startTime, String endTime) {
        Date start = com.xmb.wcapi.util.DateUtil.getDateFormat(startTime);
        Date end = com.xmb.wcapi.util.DateUtil.getDateFormat(endTime);

        //缺失天数 生成时间范围内的每一天 字符串
        List<String> everyDayToString = com.xmb.wcapi.util.DateUtil.getEveryDayToString(start, end);

        List<DutyAgo> list = new ArrayList<>();
        for (String time : everyDayToString) {
            StringBuffer buffer = new StringBuffer();
            buffer.append("?page=1&size=5000");
            //打卡日期
            buffer.append("&startDate=");
            buffer.append(time.replace("-","%2F"));
            buffer.append("&endDate=");
            buffer.append(time.replace("-","%2F"));
            //先查询 所有数据
            JSONObject data = getUniResultData(buffer.toString());
            //获取具体数据
            List<UniResultData> dataList = null;
            try {
                if (null == data){
                    continue;
                }
                dataList = JSONObject.parseArray(String.valueOf(data.get("data")), UniResultData.class);
            } catch (Exception e) {
                e.printStackTrace();
                continue;
            }
            if (null == dataList){
                continue;
            }
            //按照时间撮每一天进行分组
            Map<Long, List<UniResultData>> workDateMap = dataList.stream().collect(Collectors.groupingBy(UniResultData::getWorkDate));
            for (Long l : workDateMap.keySet()) {
                List<UniResultData> resultData = workDateMap.get(l);
                long dutyDLSum = resultData.stream().filter(pre -> pre.getDepartname().contains("员工")).count();
                long dutyIDLSum = resultData.stream().filter(pre -> !pre.getDepartname().contains("员工")).count();

                //按照班次分组
                Map<String, List<UniResultData>> shiftNames = resultData.stream().collect(Collectors.groupingBy(UniResultData::getShiftName));
                data.clear();

                DutyAgo dutyAgo = new DutyAgo();
                dutyAgo.setCardTime(com.xmb.wcapi.util.DateUtil.getDateFormat(new Date(l)));//打卡时间
                dutyAgo.setManufacturer("DONGJU");
                dutyAgo.setVendorCode("620425");
                dutyAgo.setDutyDLSum((int) dutyDLSum); //在职直接
                dutyAgo.setDutyIDLSum((int) dutyIDLSum); //在职间接
                dutyAgo.setDutySum(dutyAgo.getDutyDLSum() + dutyAgo.getDutyIDLSum()); //在职总人数
                //数据统计解析
                for (String key : shiftNames.keySet()) {
                    //是夜班的 ，其他都是白班
                    if ("夜班".equals(key)) {
                        long nightDLSum = shiftNames.get(key).stream().filter(pre -> filterDutyAgo(pre, true)).count();
                        long nightIDLSum = shiftNames.get(key).stream().filter(pre -> filterDutyAgo(pre, false)).count();
                        dutyAgo.setNightDLSum(dutyAgo.getNightDLSum() + (int) nightDLSum);
                        dutyAgo.setNightIDLSum(dutyAgo.getNightIDLSum() + (int) nightIDLSum);

                    } else {
                        long daytimeDLSum = shiftNames.get(key).stream().filter(pre -> filterDutyAgo(pre, true)).count();
                        long daytimeIDLSum = shiftNames.get(key).stream().filter(pre -> filterDutyAgo(pre, false)).count();
                        dutyAgo.setDaytimeDLSum(dutyAgo.getDaytimeDLSum() + (int) daytimeDLSum);
                        dutyAgo.setDaytimeIDLSum(dutyAgo.getDaytimeIDLSum() + (int) daytimeIDLSum);
                    }
                }
                dutyAgo.setDaytimeSum(dutyAgo.getDaytimeDLSum() + dutyAgo.getDaytimeIDLSum());
                dutyAgo.setNightSum(dutyAgo.getNightDLSum() + dutyAgo.getNightIDLSum());
                dutyAgo.setDaySum(dutyAgo.getNightSum() + dutyAgo.getDaytimeSum());
                list.add(dutyAgo);
            }
        }
        return list;
    }

    private static boolean filterDutyAgo(UniResultData pre,boolean contains){
        //排除旷工数据
        if (!(pre.getInStatus() == 3 && pre.getOutStatus() == 4)){
            //直接
            if (contains && pre.getDepartname().contains("员工")){
                return true;
            }
            //间接
            if (!contains && !pre.getDepartname().contains("员工")){
                return true;
            }
        }
        return false;
    }


    @Override
    public R invReload(String startTime, String endTime) {
        Date start = com.xmb.wcapi.util.DateUtil.getDateFormat(startTime);
        Date end = com.xmb.wcapi.util.DateUtil.getDateFormat(endTime);

        //每一天
        List<String> everyDayToString = com.xmb.wcapi.util.DateUtil.getEveryDayToString(start, end);
        //删除已存在的
        if (!everyDayToString.isEmpty()){
            dutyAgoDataMapper.delete(Wrappers.lambdaUpdate(DutyAgo.class).in(DutyAgo::getCardTime,everyDayToString));
            for (String time : everyDayToString) {
                // 执行上午
                recalculateDay(DateUtil.parseDate(time));
                // 执行下午
                recalculateNight(DateUtil.parseDate(time));
            }
        }
        return R.ok();
    }

    @Override
    public LayTableR getDutyAgoNext(Integer page, Integer limit,String startTime, String endTime) {
//        LayTableR dutyList = getDutyAgo(page, limit, startTime, endTime);
//        List<DutyAgo> list = (List<DutyAgo>) dutyList.get("data");
//        //获取人力最低值
//        List<Duty> duties = dutyMapper.selectList(Wrappers.lambdaQuery(Duty.class));
//        //最低人数
//        Map<String, Integer> mapPrice = duties.stream().collect(Collectors.toMap(Duty::getDuField, Duty::getPrice));
//        //增长人数
//        Map<String, Integer> mapGrowth = duties.stream().collect(Collectors.toMap(Duty::getDuField, Duty::getGrowth));
//        for (DutyAgo dutyAgo : list) {
//            if (dutyAgo.getDaytimeDLSum() < mapPrice.get("daytimeDLSum")){
//                dutyAgo.setDaytimeDLSum(mapPrice.get("daytimeDLSum")+mapGrowth.get("daytimeDLSum"));
//            }
//            if (dutyAgo.getDaytimeIDLSum() < mapPrice.get("daytimeIDLSum")){
//                dutyAgo.setDaytimeIDLSum(mapPrice.get("daytimeIDLSum")+mapGrowth.get("daytimeIDLSum"));
//            }
//            dutyAgo.setDaytimeSum(dutyAgo.getDaytimeDLSum()+ dutyAgo.getDaytimeIDLSum());
//
//            if (dutyAgo.getNightDLSum() < mapPrice.get("nightDLSum")){
//                dutyAgo.setNightDLSum(mapPrice.get("nightDLSum")+mapGrowth.get("nightDLSum"));
//            }
//            if (dutyAgo.getNightIDLSum() < mapPrice.get("nightIDLSum")){
//                dutyAgo.setNightIDLSum(mapPrice.get("nightIDLSum")+mapGrowth.get("nightIDLSum"));
//            }
//            dutyAgo.setNightSum(dutyAgo.getNightDLSum()+dutyAgo.getNightIDLSum());
//
//            dutyAgo.setDaySum(dutyAgo.getDaytimeSum()+ dutyAgo.getNightSum());
//            //校验是否超过了原本值
//            int dutySum = dutyAgo.getDaytimeDLSum() + dutyAgo.getNightDLSum();
//            if (dutySum > dutyAgo.getDutyDLSum()){
//                dutyAgo.setDutyDLSum(dutySum);
//            }
//            int nightSum = dutyAgo.getDaytimeIDLSum() + dutyAgo.getNightIDLSum();
//            if (nightSum > dutyAgo.getDutyIDLSum()){
//                dutyAgo.setDutyIDLSum(nightSum);
//            }
//            dutyAgo.setDutySum(dutyAgo.getDutyDLSum()+dutyAgo.getDutyIDLSum());
//
//        }
//        log.info("远程查询："+list.size());
//        //调整后添加到数据库中
//        //先判断是否已经存在日期
//        List<String> cardTimes = list.stream().map(DutyAgo::getCardTime).collect(Collectors.toList());
//        List<DutyAgo> dutyAgos;
//        log.info("cardTimes："+cardTimes.size());
//        if(!cardTimes.isEmpty()){
//            dutyAgos = dutyAgoDataMapper.selectList(Wrappers.lambdaQuery(DutyAgo.class)
//                    .in(DutyAgo::getCardTime, cardTimes)
//            );
//        } else {
//            dutyAgos = new ArrayList<>();
//        }
//        log.info("dutyAgos："+dutyAgos.size());
//        //查询到了数据
//        if (!dutyAgos.isEmpty()){
//            //获取已经存在的数据
//            //差集
//            List<DutyAgo> newList = list.stream().filter(
//                    b -> dutyAgos.stream().map(DutyAgo::getCardTime).noneMatch(card -> Objects.equals(b.getCardTime(), card))
//            ).collect(Collectors.toList());
//            log.info("newList："+newList.size());
//            if (!newList.isEmpty()){
//                for (DutyAgo dutyAgo : newList) {
//                    dutyAgoDataMapper.insert(dutyAgo);
//                }
//            }
//        }else {
//            //写入数据库
//            for (DutyAgo dutyAgo : list) {
//                dutyAgoDataMapper.insert(dutyAgo);
//            }
//        }

        //添加过后重新查询
        Page<DutyAgo> dutyAgoPage = dutyAgoDataMapper.selectPage(new Page<>(page, limit), Wrappers.lambdaQuery(DutyAgo.class)
                .between(DutyAgo::getCardTime, startTime, endTime)
                .orderByDesc(DutyAgo::getCardTime)
        );

        return LayTableR.result(0,dutyAgoPage.getTotal(),dutyAgoPage.getRecords());
    }

    //上午
    public void recalculateDay(Date time){

        //判断登录
        loginDuty();

        String format = DateUtil.format(time, "yyyy-MM-dd");

        //执行请求
        StringBuffer buffer = new StringBuffer();
        buffer.append("?startDate=");
        buffer.append(format.replace("-","%2F"));
        buffer.append("&endDate=");
        buffer.append(format.replace("-","%2F"));

        // 查询今天的考勤
        buffer.append("&page=1&size=5000");

        //先查询 所有数据
        JSONObject data = getUniResultData(buffer.toString());
        //获取具体数据
        List<UniResultData> dataList = null;
        try {
            dataList = JSONObject.parseArray(String.valueOf(data.get("data")), UniResultData.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (null == dataList){
            return;
        }

        // 数据统计
        long dutyDLSum = dataList.stream().filter(pre -> pre.getDepartname().contains("员工")).count();
        long dutyIDLSum = dataList.stream().filter(pre -> !pre.getDepartname().contains("员工")).count();

        //按照班次分组
        Map<String, List<UniResultData>> shiftNames = dataList.stream().collect(Collectors.groupingBy(UniResultData::getShiftName));

        DutyAgo dutyAgo = new DutyAgo();
        dutyAgo.setCardTime(DateUtil.format(time,"yyyy-MM-dd"));//打卡时间
        dutyAgo.setManufacturer("DONGJU");
        dutyAgo.setVendorCode("620425");
        dutyAgo.setDutyDLSum((int) dutyDLSum); //在职直接
        dutyAgo.setDutyIDLSum((int) dutyIDLSum); //在职间接
        dutyAgo.setDutySum(dutyAgo.getDutyDLSum() + dutyAgo.getDutyIDLSum()); //在职总人数
        //数据统计解析
        for (String key : shiftNames.keySet()) {
            //是夜班的 ，其他都是白班
            if ("夜班".equals(key)) {
                long nightDLSum = shiftNames.get(key).stream().filter(pre -> filterDutyAgo(pre, true)).count();
                long nightIDLSum = shiftNames.get(key).stream().filter(pre -> filterDutyAgo(pre, false)).count();
                dutyAgo.setNightDLSum(dutyAgo.getNightDLSum() + (int) nightDLSum);
                dutyAgo.setNightIDLSum(dutyAgo.getNightIDLSum() + (int) nightIDLSum);

            } else {
                long daytimeDLSum = shiftNames.get(key).stream().filter(pre -> filterDutyAgo(pre, true)).count();
                long daytimeIDLSum = shiftNames.get(key).stream().filter(pre -> filterDutyAgo(pre, false)).count();
                dutyAgo.setDaytimeDLSum(dutyAgo.getDaytimeDLSum() + (int) daytimeDLSum);
                dutyAgo.setDaytimeIDLSum(dutyAgo.getDaytimeIDLSum() + (int) daytimeIDLSum);
            }
        }
        dutyAgo.setDaytimeSum(dutyAgo.getDaytimeDLSum() + dutyAgo.getDaytimeIDLSum());
        dutyAgo.setNightSum(dutyAgo.getNightDLSum() + dutyAgo.getNightIDLSum());
        dutyAgo.setDaySum(dutyAgo.getNightSum() + dutyAgo.getDaytimeSum());

        // 调整
        adjustDuty(dutyAgo);

        dutyAgoDataMapper.delete(Wrappers.lambdaUpdate(DutyAgo.class).eq(DutyAgo::getCardTime, dutyAgo.getCardTime()));
        dutyAgoDataMapper.insert(dutyAgo);

    }

    // 下午
    public void recalculateNight(Date time){
        //判断登录
        loginDuty();

        String format = DateUtil.format(time, "yyyy-MM-dd");

        //执行请求
        StringBuffer buffer = new StringBuffer();
        buffer.append("?startDate=");
        buffer.append(format.replace("-","%2F"));
        buffer.append("&endDate=");
        buffer.append(format.replace("-","%2F"));

        // 查询今天的考勤
        buffer.append("&page=1&size=5000");

        //先查询 所有数据
        JSONObject data = getUniResultData(buffer.toString());
        //获取具体数据
        List<UniResultData> dataList = null;
        try {
            dataList = JSONObject.parseArray(String.valueOf(data.get("data")), UniResultData.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (null == dataList){
            return;
        }

        // 数据统计
        long dutyDLSum = dataList.stream().filter(pre -> pre.getDepartname().contains("员工")).count();
        long dutyIDLSum = dataList.stream().filter(pre -> !pre.getDepartname().contains("员工")).count();

        //按照班次分组
        Map<String, List<UniResultData>> shiftNames = dataList.stream().collect(Collectors.groupingBy(UniResultData::getShiftName));

        DutyAgo dutyAgo = new DutyAgo();
        dutyAgo.setCardTime(DateUtil.format(time,"yyyy-MM-dd"));//打卡时间
        dutyAgo.setManufacturer("DONGJU");
        dutyAgo.setVendorCode("620425");
        dutyAgo.setDutyDLSum((int) dutyDLSum); //在职直接
        dutyAgo.setDutyIDLSum((int) dutyIDLSum); //在职间接
        dutyAgo.setDutySum(dutyAgo.getDutyDLSum() + dutyAgo.getDutyIDLSum()); //在职总人数
        //数据统计解析
        for (String key : shiftNames.keySet()) {
            //是夜班的 ，其他都是白班
            if ("夜班".equals(key)) {
                long nightDLSum = shiftNames.get(key).stream().filter(pre -> filterDutyAgo(pre, true)).count();
                long nightIDLSum = shiftNames.get(key).stream().filter(pre -> filterDutyAgo(pre, false)).count();
                dutyAgo.setNightDLSum(dutyAgo.getNightDLSum() + (int) nightDLSum);
                dutyAgo.setNightIDLSum(dutyAgo.getNightIDLSum() + (int) nightIDLSum);

            } else {
                long daytimeDLSum = shiftNames.get(key).stream().filter(pre -> filterDutyAgo(pre, true)).count();
                long daytimeIDLSum = shiftNames.get(key).stream().filter(pre -> filterDutyAgo(pre, false)).count();
                dutyAgo.setDaytimeDLSum(dutyAgo.getDaytimeDLSum() + (int) daytimeDLSum);
                dutyAgo.setDaytimeIDLSum(dutyAgo.getDaytimeIDLSum() + (int) daytimeIDLSum);
            }
        }
        dutyAgo.setDaytimeSum(dutyAgo.getDaytimeDLSum() + dutyAgo.getDaytimeIDLSum());
        dutyAgo.setNightSum(dutyAgo.getNightDLSum() + dutyAgo.getNightIDLSum());
        dutyAgo.setDaySum(dutyAgo.getNightSum() + dutyAgo.getDaytimeSum());

        // 调整
        adjustDuty(dutyAgo);

        dutyAgoDataMapper.delete(Wrappers.lambdaUpdate(DutyAgo.class).eq(DutyAgo::getCardTime, format));
        dutyAgoDataMapper.insert(dutyAgo);

    }

    private void adjustDuty(DutyAgo dutyAgo){
        //获取人力最低值
        List<Duty> duties = dutyMapper.selectList(Wrappers.lambdaQuery(Duty.class));
        //最低人数
        Map<String, Integer> mapPrice = duties.stream().collect(Collectors.toMap(Duty::getDuField, Duty::getPrice));
        //增长人数
        Map<String, Integer> mapGrowth = duties.stream().collect(Collectors.toMap(Duty::getDuField, Duty::getGrowth));

        if (dutyAgo.getDaytimeDLSum() < mapPrice.get("daytimeDLSum")){
            dutyAgo.setDaytimeDLSum(mapPrice.get("daytimeDLSum")+mapGrowth.get("daytimeDLSum"));
        }
        if (dutyAgo.getDaytimeIDLSum() < mapPrice.get("daytimeIDLSum")){
            dutyAgo.setDaytimeIDLSum(mapPrice.get("daytimeIDLSum")+mapGrowth.get("daytimeIDLSum"));
        }
        dutyAgo.setDaytimeSum(dutyAgo.getDaytimeDLSum()+ dutyAgo.getDaytimeIDLSum());

        if (dutyAgo.getNightDLSum() < mapPrice.get("nightDLSum")){
            dutyAgo.setNightDLSum(mapPrice.get("nightDLSum")+mapGrowth.get("nightDLSum"));
        }
        if (dutyAgo.getNightIDLSum() < mapPrice.get("nightIDLSum")){
            dutyAgo.setNightIDLSum(mapPrice.get("nightIDLSum")+mapGrowth.get("nightIDLSum"));
        }
        dutyAgo.setNightSum(dutyAgo.getNightDLSum()+dutyAgo.getNightIDLSum());

        dutyAgo.setDaySum(dutyAgo.getDaytimeSum()+ dutyAgo.getNightSum());
        //校验是否超过了原本值
        int dutySum = dutyAgo.getDaytimeDLSum() + dutyAgo.getNightDLSum();
        if (dutySum > dutyAgo.getDutyDLSum()){
            dutyAgo.setDutyDLSum(dutySum);
        }
        int nightSum = dutyAgo.getDaytimeIDLSum() + dutyAgo.getNightIDLSum();
        if (nightSum > dutyAgo.getDutyIDLSum()){
            dutyAgo.setDutyIDLSum(nightSum);
        }
        dutyAgo.setDutySum(dutyAgo.getDutyDLSum()+dutyAgo.getDutyIDLSum());

    }
}
